﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Web;

namespace SmartSpace.WebApp._console.core.common
{
	public partial class usergroup_privilege_assign : System.Web.UI.Page
	{
        private Guid _groupId;

		protected void Page_Load(object sender, EventArgs e)
		{
            _groupId = Request.GetGuid("id");
            if (_groupId == default(Guid))
            {
                Response.Redirect("./usergroup-list.aspx");
            }
		}

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();
            //UserGroup group = service.GetUserGroup(_groupId);

            foreach (RepeaterItem item in _ctlList.Items)
            {
                CheckBox checkBox = (CheckBox)item.FindControl("_ctlCheck");
                if (checkBox != null && checkBox.Checked)
                {
                    HiddenField hiddenField = (HiddenField)item.FindControl("_ctlTag");
                    Guid privilegeId = new Guid(hiddenField.Value);
                    if (service.AssignPrivilege(privilegeId, _groupId, PrivilegeOwnerType.UserGroup).IsSuccess)
                    {
                        Logger.Info(string.Format("assign privilege {0} to usergroup {1} success!", privilegeId, _groupId));
                    }
                    else
                    {
                        Logger.Error(string.Format("assign privilege {0} to usergroup {1} failure!", privilegeId, _groupId));
                    }
                }
            }

            SsPage.Return(this, new { success = true });
        }

        protected void _ctlBtnSearch_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();
            List<Privilege> privileges = service.GetPrivileges(_ctlEditCode.Text, 0, 999);
            _ctlList.DataSource = privileges;
            _ctlList.DataBind();
        }
	}
}